[JavaScript] ES6:Template Literals 樣板字面值


Posted by Nicolakacha on 2020-09-05

Template Literals 樣板字面值

樣板字面值的構成為兩個反引號 `` 來封閉,內部可用佔位符 ${} 來傳入變數或函式:

`string text ${expression}`

解決的問題:

  1. 若需要一個字串和變數的組合,不再需要使用字串拼接的方式:

    let originString = 'My name is ' + people[0].name + '.';
    let literalString = `My name is ${ peoplep[2].name } .`;
    
  2. 多行字串,不再需要用 \n 和 + 來拼接

    let template = 'hello 1\n' +
    'word';
    console.log(template);
    // "hello
    // world"
    
    let template = `string text line 1
    string text line 2`;
    console.log(template);
    // "hello
    // world"
    
  3. 實現巢狀結構

    const person = {
    name: '小明'
    cash: 1000
    }
    const sentence = `我是${person.name},${`身上帶有 ${ person.cash }` }元`
    // 我是小明,身上帶有1000元
    
  4. 在字串中加入運算式可直接內插,不用拼接

    let a = 5;
    let b = 10;
    console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);
    // "Fifteen is 15 and not 20."
    
  5. 標籤樣板字面值,透過標籤函數操作字面值的輸出,第一個參數是一個字串陣列,其餘參數是處理過的表達式,可以返回經過處理的字串或是其他東西。

    var person = 'Mike';
    var age = 28;
    function myTag(strings, personExp, ageExp) {
    var str0 = strings[0]; // "that "
    var str1 = strings[1]; // " is a "
    var ageStr;
    if (ageExp > 99){
     ageStr = 'centenarian';
    } else {
     ageStr = 'youngster';
    }
    return str0 + personExp + str1 + ageStr;
    }
    var output = myTag`that ${ person } is a ${ age }`;
    console.log(output);
    // that Mike is a youngster
    

#ES6 #javascript #template literals #樣板字面值







Related Posts

Debounce & Throttle in React - 1

Debounce & Throttle in React - 1

來學 React 吧之七_React 實作留言板

來學 React 吧之七_React 實作留言板

Spring boot系列(一)前言

Spring boot系列(一)前言


Comments